package com.hyc.sso_server.utils;

import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @projectName: SSO_self
 * @package: com.hyc.http
 * @className: HttpUitl
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/1/9 0:52
 * @version: 1.0
 */
public class HttpUitl {
    public static String sendHttpRequest(String httpurl, Map<String, String> parms) throws Exception {
        //定义需要访问的地址
        URL url = new URL(httpurl);
        //连接 URL
        HttpURLConnection connect = (HttpURLConnection) url.openConnection();
        //请求方式
        connect.setRequestMethod("POST");
        //携带参数
        connect.setDoOutput(true);
        if (parms != null && parms.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> par : parms.entrySet()) {
                sb.append("&").append(par.getKey()).append("=").append(par.getValue());
            }
            connect.getOutputStream().write(sb.substring(1).toString().getBytes("UTF-8"));
        }
        // 发起请求
        connect.connect();
        //接受返回值
        String response = StreamUtils.copyToString(connect.getInputStream(), Charset.forName("UTF-8"));
        return response;
    }
}
